const http = require("http");
const fs = require("fs");
const path = require("path");
const { URL } = require("url");
const querystring = require("querystring");

http.createServer((req, res) => {
    let urlObj = new URL(req.url , "http:192.168.42.166:3000");
    let reqPath = urlObj.pathname;
    console.log(reqPath);
    if(reqPath === '/') {
        let fileContent = fs.readFileSync(path.join(__dirname , "index.html"));
        res.end(fileContent);
    } else if(reqPath.indexOf("/image") >= 0) {
        console.log(path.join(__dirname , reqPath));
        let imageContent = fs.readFileSync(path.join(__dirname , reqPath));
        res.end(imageContent);
    } else if(reqPath.indexOf("/upload") >= 0) {
        req.setEncoding("binary");
        let str = '';
        req.on("data" , (chunk) => {
            str += chunk;
        });
        req.on("end" , () => {
            fs.writeFileSync("load.txt" , str , {encoding: "binary"});
            // console.log(str.split("\r\n"));
            let arr = str.split("\r\n");
            // let objStr = arr.slice(4).join("");
            // let fileInfo = arr[1];
            // console.log(arr[0]);
            let Arr = str.split(arr[0]);
            console.log(Arr);
            // console.log(Arr[1].split('\r\n'));
            // console.log(Arr[1].split('\r\n')[2].split('/')[1]);
            // console.log(Arr[2].split('\r\n')[3]);
            // console.log(Arr[2].split('\r\n')[2]);
            console.log(Arr.length);
            for(let i = 1 ; i < Arr.length - 1 ; i++) {
                let objStr = Arr[i].split('\r\n').slice(4).join("");
                console.log(Arr[i].split('\r\n')[1]);
                console.log(Arr[i].split('\r\n')[2]);
                let fileName = Date.now() + '.' + Arr[i].split('\r\n')[2].split('/')[1];
                let filePath = path.join(__dirname , "upload/" + fileName);
                fs.writeFileSync(filePath , objStr , {encoding: "binary"});
            }
            // console.log(arr[2].split('/')[1]);
            // console.log(querystring.parse(fileInfo)['Content-Disposition: form-data; name'].lastIndexOf("filename"));
            // console.log(querystring.parse(fileInfo)['Content-Disposition: form-data; name']);
            // console.log(querystring.parse(fileInfo)['Content-Disposition: form-data; name'].slice(querystring.parse(fileInfo)['Content-Disposition: form-data; name'].lastIndexOf("filename")));
            // console.log(querystring.parse(fileInfo)['Content-Disposition: form-data; name'].slice(querystring.parse(fileInfo)['Content-Disposition: form-data; name'].lastIndexOf("filename")).split("=")[1]);
            // let fileName = querystring.parse(fileInfo)['Content-Disposition: form-data; name'].slice(querystring.parse(fileInfo)['Content-Disposition: form-data; name'].lastIndexOf("filename")).split("=")[1]
            let fileName = Date.now() + '.' + arr[2].split('/')[1];
            console.log(fileName);
            let filePath = path.join(__dirname , "upload/" + fileName)
            // fs.writeFileSync(filePath , objStr , {encoding: "binary"});
        })
    } else if (reqPath.indexOf("/list") >= 0) {
        let fileContent = fs.readFileSync(path.join(__dirname , "list.html"));
        res.end(fileContent);
    } else if (reqPath.indexOf("/show") >= 0) {
        let fileArr = fs.readdirSync(path.join(__dirname , "upload"));
        // let fileContentArr = [];
        // fileArr.forEach(item => {
        //     fileContentArr.push(fs.readFileSync(path.join(path.join(__dirname, "upload") , item)));
        // })
        res.end(JSON.stringify(fileArr))
    } else if (reqPath.indexOf("/pic") >= 0) {
        console.log(urlObj.pathname);
        console.log(urlObj.pathname.split('/')[2]);
        let filePath = path.join(path.join(__dirname , "upload") , urlObj.pathname.split('/')[2]);
        let fileContent = fs.readFileSync(filePath);
        res.end(fileContent);
    }
}).listen(3000);